package dk.javacode.srsm.converters;


public class BooleanJdbcConverter implements JdbcDataConverter<Boolean> {

	@Override
	public Boolean convertToPojo(Object o) {
		if (o == null) {
			return null;
		}
		if (o instanceof Number) {
			Number n = (Number) o;
			return n.intValue() != 0;
		}
		if (!(o instanceof String)) {
			throw new RuntimeException("Unable to convert non-string to boolean");
		}
		try {
			String s = (String) o;
			if (s.equalsIgnoreCase("y") || s.equalsIgnoreCase("yes")) {
				return true;
			}
			return Boolean.parseBoolean("" + o);
		} catch (Exception e) {
			throw new RuntimeException("Unable to parse boolean");
		}
	}

	@Override
	public Object pojoToDatabase(Object o) {
		if (o == null) {
			return null;
		}
		return ((Boolean) o) ? "Y" : "N";
	}

	
}
